// @flow
import React from 'react'
import { Modal, Form, Input, Button, Checkbox, Select, DatePicker, message } from 'antd'
import { connect } from 'react-redux'
import universalFetch from 'store/modules/fetch'
import styles from './HistoryPop.css'
const FormItem = Form.Item
const RangePicker = DatePicker.RangePicker
const Option = Select.Option

type Props = {
  deviceCard: Object,
  form: Object,
  onChange: Function
}

type State = {
  loading: boolean,
  visible: boolean,
  groupId: string
}

class HistoryPop extends React.Component {
  props: Props
  state: State
  showModal: Function
  handleOk: Function
  handleCancel: Function
  handleSubmit: Function

  constructor (props: Object) {
    super(props)
    this.state = {
      loading: false,
      visible: false,
      groupId: this.props.deviceCard.groupId
    }
    this.showModal = this.showModal.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  handleSubmit (e) {
    e.preventDefault()
    // console.log('收到表单值：', this.props.form.getFieldsValue())
  }

  showModal () {
    this.setState({
      visible: true
    })
  }

  handleOk () {
    let formValue = this.props.form.getFieldsValue()
    formValue['deviceId'] = this.props.deviceCard.deviceData.id
    formValue['startTime'] = formValue.eventTime[0]
    formValue['endTime'] = formValue.eventTime[1]

    universalFetch(`${__SERVICE_API__}device/events`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formValue)
    })
      .then((res) => res.json())
      .then((json) => {
        this.setState({ loading: false, visible: false })
        if (json.code === 200000) {
          message.success('事件添加成功')
          this.props.onChange()
        } else {
          message.error('事件添加失败，请重新添加')
        }
      })
  }

  handleCancel () {
    this.setState({ visible: false })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    }
    const singleItemLayout = {
      wrapperCol: {
        span: 24,
        offset: 6
      }
    }
    return (
      <div className={styles['pop']}>
        <Button type='primary' onClick={this.showModal}>
          添加事件
        </Button>
        <Modal ref='modal'
          visible={this.state.visible}
          title='添加事件' onOk={this.handleOk} onCancel={this.handleCancel}
          footer={[
            <Button key='back' type='ghost' onClick={this.handleCancel}>返 回</Button>,
            <Button key='submit' type='primary' loading={this.state.loading} onClick={this.handleOk}>
              提 交
            </Button>
          ]}>
          <Form onSubmit={this.handleSubmit}>
            <FormItem
              {...formItemLayout}
              label='事件类型'>
              {getFieldDecorator('eventType')(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择事件类型'>
                  <Option value='停机'>停机</Option>
                  <Option value='开机'>开机</Option>
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='事件时间'>
              {getFieldDecorator('eventTime')(
                <RangePicker style={{ width: 'auto' }}
                  showTime format='YYYY-MM-DD HH:mm:ss' />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              style={{ marginBottom: '6px' }}
              label='处理状态'>
              {getFieldDecorator('status')(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择处理状态'>
                  <Option value='未处理'>未处理</Option>
                  <Option value='已处理'>已处理</Option>
                  <Option value='生成工单'>生成工单</Option>
                </Select>
              )}
            </FormItem>
            <FormItem
              label=''
              style={{ marginBottom: '6px' }}
              {...singleItemLayout}>
              {
                getFieldDecorator('eventRecord')(
                  <Checkbox>生成检修记录</Checkbox>
                )
              }
            </FormItem>
            <FormItem
              {...formItemLayout}
              label='事件描述'>
              {getFieldDecorator('detail')(
                <Input type='textarea' placeholder='请填写事件描述' />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard
  }
}
export default connect(mapStatesToProps, {})(Form.create()(HistoryPop))
